package com.kummuna.ui;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.facebook.FacebookException;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.LoginButton.OnErrorListener;
import com.kummuna.R;
import com.kummuna.util.facebook.UserFunctions;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

public class MainFragment extends Fragment {
	private static final String TAG = "MainFragment";
	private UiLifecycleHelper uiHelper;

	public interface FBAuthenListener {
		public void onSuccess();
	}

	List<FBAuthenListener> listeners = new ArrayList<FBAuthenListener>();

	// a way to add someone to the list of catchers
	public void addThrowListener(FBAuthenListener toAdd) {
		listeners.add(toAdd);
	}

	private void RaiseSuccess() {
		// 1 or more times, a Notification that an event happened is thrown.
		for (FBAuthenListener hl : listeners)
			hl.onSuccess();
	}

	private Session.StatusCallback callback = new Session.StatusCallback() {
		@Override
		public void call(Session session, SessionState state,
				Exception exception) {
			onSessionStateChage(session, state, exception);
		}

	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		uiHelper = new UiLifecycleHelper(getActivity(), callback);
		uiHelper.onCreate(savedInstanceState);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater
				.inflate(R.layout.activity_log_on, container, false);

		Session session = Session.getActiveSession();

		if (session != null && session.isOpened()) {
			RaiseSuccess();
		} else{
			LoginButton authButton = (LoginButton) view
					.findViewById(R.id.authButton);
			authButton.setFragment(this);
			
			authButton.setOnErrorListener(new OnErrorListener() {
				@Override
				public void onError(FacebookException error) {
					Log.i(TAG, "FaceBook Error " + error.getMessage());
				}
			});
		}

		// authButton.setReadPermissions(Arrays.asList("user_likes",
		// "user_status"));
		return view;
	}

	private void onSessionStateChage(Session session, SessionState state,
			Exception exeception) {
		if (state.isOpened()) {
			RaiseSuccess();
			Log.i(TAG, "Logged in...");
			// make request to the /me API
			Request request = Request.newMeRequest(session,
					new Request.GraphUserCallback() {
						// callback after Graph API response with user object

						@Override
						public void onCompleted(GraphUser user, Response response) {
							// TODO Auto-generated method stub
							if (user != null) {
								
								UserFunctions func=new UserFunctions();
								String imageUrl = "http://graph.facebook.com/"+user.getId()+"/picture?type=large";
				                JSONObject getUserjson=func.loginUser(user.getName(), user.getId(), imageUrl);
								Log.i(TAG,
										user.getName() + ","
												+ user.getUsername() + ","
												+ user.getId() + ","
												+ user.getLink() + ","
												+ user.getFirstName()
												+ user.asMap().get("email"));
								Log.i(TAG, imageUrl);
								try {
									final String uid=getUserjson.getJSONObject("Data").getString("Id");
									final String uname=getUserjson.getJSONObject("Data").getString("Name");
						            final String img=getUserjson.getJSONObject("Data").getString("Image");
						            Log.i(TAG, "id: " + uid + ", name: " + uname + ", img: " + img);
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
					            
							}
						}
					});
			Request.executeBatchAsync(request);

			// Toast.makeText(getActivity(),"Logged in...",Toast.LENGTH_SHORT).show();

		} else if (state.isClosed()) {
			Log.i(TAG, "Logged out...");
			Toast.makeText(getActivity(), "Logged out...", Toast.LENGTH_SHORT)
					.show();
		}
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		// For scenarios where the main activity is launched and user
		// session is not null, the session state chage notification
		// may not be triggered. Trigger it if it's open/closed

		/*
		 * Session session = Session.getActiveSession();
		 * 
		 * if (session != null && (session.isOpened() || session.isClosed())) {
		 * onSessionStateChage(session, session.getState(), null); }
		 */
		uiHelper.onResume();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		uiHelper.onActivityResult(requestCode, resultCode, data);
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	
	public void onSuccess() {
		// TODO Auto-generated method stub
		Intent Gmap = new Intent(getActivity(), Detectivemap.class);
		Gmap.putExtra("uid", "");
		Gmap.putExtra("uname", "");
		Gmap.putExtra("img", "");
		Gmap.putExtra("flag", "1");
		startActivityForResult(Gmap, 1);
		// startActivity(Gmap);
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		uiHelper.onPause();
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		uiHelper.onDestroy();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		uiHelper.onSaveInstanceState(outState);
	}
}
